<?php

namespace app\admin\model;
use think\facade\Db;
use think\Model;

/**
 * Order
 */
class Order extends Model
{
    // 表主键
    protected $pk = 'oid';

    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $createTime = 'timestamp'; // 自定义创建时间字段名

    // 字段类型转换
    protected $type = [
        'timestamp' => 'timestamp:Y-m-d H:i:s',
        'pay_time'  => 'timestamp:Y-m-d H:i:s',
    ];


    public function admin(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'agent_id', 'id');
    }
     public function market(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Admin::class, 'dealer_id', 'id');
    }
    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\User::class, 'uid', 'id');
    }
    public function device(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\Device::class, 'device_code', 'id');
    }


    // 在插入前自动获取代理id 经销商id
    protected static function onBeforeInsert($device)
    {
        if (!empty($device->device_code)) {
            $res = Db::name('device')
                ->where('id', $device->device_code)
                ->field('agent_id,market_id')->find();

            $device->agent_id= $res['agent_id'];
            $device->dealer_id= $res['market_id'];
        }
        
    }

}